package ru.p03.tvipuskeditor.client.tvipuskeditor;

import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

//import ru.p03.tvipusk.cursortest.TimeHelper;

//import org.gwtwidgets.client.util.SimpleDateFormat;

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.Text;
import com.google.gwt.xml.client.XMLParser;

public class BlockFactory {
 
//	private Block block;

//  private Element generateXml() throws ParserConfigurationException {

    public static String generateXml(Block rootBlock)  {

    	Document dom;
        dom = XMLParser.createDocument();

        Element rootBlockTag = dom.createElement("block");
        rootBlockTag.setAttribute("id", rootBlock.getId());
        rootBlockTag.setAttribute("title", rootBlock.getBlockAtrTitle());
        rootBlockTag.setAttribute("type", rootBlock.getBlockAtrType());
//        rootBlockTag.setAttribute("file_name", rootBlock.getFileName());
//        rootBlockTag.setAttribute("file_duration", rootBlock.getDuration());
//        rootBlockTag.setAttribute("file_s", rootBlock.getS());
//        rootBlockTag.setAttribute("file_po", rootBlock.getPo());
        Element fileTag = dom.createElement("file");
        fileTag.setAttribute("name", rootBlock.getFileName());
        fileTag.setAttribute("duration", rootBlock.getDuration());
        fileTag.setAttribute("s", rootBlock.getS());
        fileTag.setAttribute("po", rootBlock.getPo());
        rootBlockTag.appendChild(fileTag);

        Element textTag = dom.createElement("text");
        Text textTagNode = dom.createTextNode(rootBlock.getText());
        textTag.appendChild(textTagNode);        
        rootBlockTag.appendChild(textTag);
        
        dom.appendChild(rootBlockTag);

        if ((rootBlock.getBlocks() != null) && (! rootBlock.getBlocks().isEmpty())){
        	Element blocksTag = dom.createElement("blocks");	        
	        
	        for(Block block : rootBlock.getBlocks()){
	        	Element doc= dom.createElement("block");
	            doc.setAttribute("id", block.getId()); 
	            doc.setAttribute("title", block.getBlockAtrTitle());
	            doc.setAttribute("type", block.getBlockAtrType());

	            fileTag = dom.createElement("file");
	            fileTag.setAttribute("name", block.getFileName());
	            fileTag.setAttribute("duration", block.getDuration());
	            fileTag.setAttribute("s", block.getS());
	            fileTag.setAttribute("po", block.getPo());
	            doc.appendChild(fileTag);

	            blocksTag.appendChild(doc);
	
	            Element stextTag = dom.createElement("text");
	            Text stextTagNode = dom.createTextNode(block.getText());
	            stextTag.appendChild(stextTagNode);
	            doc.appendChild(stextTag);
	
	            if ((block.getBlocks() != null) && (! block.getBlocks().isEmpty())){
	            	Element subBlocksTag = dom.createElement("blocks");
	            	for(Block subBlock :block.getBlocks()){
	            		Element subBlockTag = dom.createElement("block");
	            		
	            		subBlockTag.setAttribute("id", subBlock.getId()); 
	            		subBlockTag.setAttribute("title", subBlock.getBlockAtrTitle());
	            		subBlockTag.setAttribute("type", subBlock.getBlockAtrType());
//	            		subBlockTag.setAttribute("file_name", subBlock.getFileName());
//	            		subBlockTag.setAttribute("file_duration", subBlock.getDuration());
//	            		subBlockTag.setAttribute("file_s", subBlock.getS());
//	            		subBlockTag.setAttribute("file_po", subBlock.getPo());

	    	            fileTag = dom.createElement("file");
	    	            fileTag.setAttribute("name", subBlock.getFileName());
	    	            fileTag.setAttribute("duration", subBlock.getDuration());
	    	            fileTag.setAttribute("s", subBlock.getS());
	    	            fileTag.setAttribute("po", subBlock.getPo());
	    	            subBlockTag.appendChild(fileTag);

	                    stextTag = dom.createElement("text");
	                    stextTagNode = dom.createTextNode(subBlock.getText());
	                    stextTag.appendChild(stextTagNode);
	                    subBlockTag.appendChild(stextTag);
	                    
	                    subBlocksTag.appendChild(subBlockTag);
	            	}
	            	doc.appendChild(subBlocksTag);
	            }
	            blocksTag.appendChild(doc);
	        }
	        rootBlockTag.appendChild(blocksTag);
        }
        return dom.toString();
    }
	
//	@Override
//	public String toString(){
//            String xmlString = new String();
//            try {
//                generateXml();
//                //OutputFormat format = new OutputFormat(dom,"utf-8", true);
//                OutputFormat format = new OutputFormat(dom,"utf-8", true);
//                format.setIndenting(true);
//                //format.setEncoding("cp866");
//                //to generate output to console use this serializer
//                //to generate a file output use fileoutputstream instead of system.out
//                FileOutputStream fos = new FileOutputStream("ready.xml");
//
//                OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
//
//                XMLSerializer serializer = new XMLSerializer(osw, format);
//                serializer.serialize(dom);
//
//                osw.close();
//                fos.close();
//            } catch (FileNotFoundException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (UnsupportedEncodingException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (ParserConfigurationException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//
//            StringWriter stringOut = new StringWriter();
//            if (dom!=null) {
//                OutputFormat opfrmt = new OutputFormat(dom/*, "UTF-8", true*/);
//                opfrmt.setIndenting(true);
//                opfrmt.setPreserveSpace(false);
//                opfrmt.setLineWidth(500);
//                XMLSerializer serial = new XMLSerializer(stringOut, opfrmt);
//                try {
//                    serial.asDOMSerializer();
//                    serial.serialize(dom);
//                    xmlString = stringOut.toString();
//                } catch(java.io.IOException ioe) {
//                    xmlString=null;
//                }
//            } else 
//                xmlString=null;
//            return xmlString;
//	}
	
//        public static Block toBlock(String xml) throws ParserConfigurationException, SAXException, IOException {
	public static Block toBlock(String xml) {
		Block rootBlock = new Block();
		if (xml.trim().isEmpty()) {
			return rootBlock;
		}
		// DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
		// dbf.setNamespaceAware(true);
		// dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
		// "http://www.w3.org/2001/XMLSchema");
		// DocumentBuilder db = dbf.newDocumentBuilder();
		// Document document = db.parse(new InputSource(new StringReader(xml)));
		// &#160;, или, что одно и то же &#xA0;
		// xml = xml.replaceAll("&nbsp;", "&#160;");

		Document document = XMLParser.parse(xml);

		document.getDocumentElement().normalize();

		// System.out.println("Root element :" +
		// document.getDocumentElement().getNodeName());
		NodeList nList = document.getElementsByTagName("block");

		Node nNode = nList.item(0);
		Element eElement = (Element) nNode;
		rootBlock.setId(eElement.getAttribute("id"));
		rootBlock.setBlockAtrTitle(eElement.getAttribute("title"));
		rootBlock.setBlockAtrType(eElement.getAttribute("type"));
		rootBlock.setText(getTagValue("text", eElement));
		Block block = null;

		NodeList bList = eElement.getElementsByTagName("block");
		
		for (int temp = 0; temp < bList.getLength(); temp++) {
			nNode = bList.item(temp);

			if (nNode.getNodeType() == Node.ELEMENT_NODE) {
				eElement = (Element) nNode;

				// System.out.println("title :" + eElement.getAttribute("title")
				// + " type: " + eElement.getAttribute("type"));
				block = new Block();
				block.setId(eElement.getAttribute("id"));
				block.setBlockAtrTitle(eElement.getAttribute("title"));
				block.setBlockAtrType(eElement.getAttribute("type"));
				
				if (TvipuskEditorWidget.SKL_TEXT.equals(block.getBlockAtrType())){
					continue;
				}
				// System.out.println("		text : " + getTagValue("text",
				// eElement));
				block.setText(getTagValue("text", eElement));

				// System.out.println("		file : " + getTagValue("file",
				// eElement));
				// block.setFileName(getTagValue("file", eElement));
				// String s = eElement.getAttribute("file_duration");
				// //Time t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				// block.setDuration(s);
				//
				// block.setFileName(eElement.getAttribute("file_name"));
				// s = eElement.getAttribute("file_po");
				// //Time t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				// block.setPo(s);
				// s = eElement.getAttribute("file_s");
				// //t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				// block.setS(s);

				String name = getTag("file", eElement).getAttribute("name");
				block.setFileName(name);

				String s = getTag("file", eElement).getAttribute("s");
				// //Time t = s.isEmpty() ? TimeHelper.zero() : Time.valueOf(s);
				// Time t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				block.setS(s);

				s = getTag("file", eElement).getAttribute("po");
				// //t = s.isEmpty() ? TimeHelper.zero() : Time.valueOf(s);
				// t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				block.setPo(s);

				s = getTag("file", eElement).getAttribute("duration");
				// //t = s.isEmpty() ? TimeHelper.zero() : Time.valueOf(s);
				// t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
				block.setDuration(s);

				NodeList snList = eElement.getElementsByTagName("block");
				// System.out.println("		blocks count : " + snList.getLength());
				List<Block> list = new ArrayList<Block>();
				// System.out.println(">>>");
				for (int temp1 = 0; temp1 < snList.getLength(); temp1++) {
					nNode = snList.item(temp1);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						eElement = (Element) nNode;
						Block bbb = new Block();

						// System.out.println("title :" +
						// eElement.getAttribute("title") + " type: " +
						// eElement.getAttribute("type"));
						bbb.setId(eElement.getAttribute("id"));
						bbb.setBlockAtrTitle(eElement.getAttribute("title"));
						bbb.setBlockAtrType(eElement.getAttribute("type"));

						// System.out.println("		text : " + getTagValue("text",
						// eElement));
						bbb.setText(getTagValue("text", eElement));

						// //System.out.println("		file : " +
						// getTagValue("file", eElement));
						// s = eElement.getAttribute("file_duration");
						// //t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						// bbb.setDuration(s);
						//
						// bbb.setFileName(eElement.getAttribute("file_name"));
						// s = eElement.getAttribute("file_po");
						// //t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						// bbb.setPo(s);
						// s = eElement.getAttribute("file_s");
						// //t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						// bbb.setS(s);

						name = getTag("file", eElement).getAttribute("name");
						bbb.setFileName(name);
						//
						s = getTag("file", eElement).getAttribute("s");
						// // t = s.isEmpty() ? TimeHelper.zero() :
						// Time.valueOf(s);
						// t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						bbb.setS(s);
						//
						s = getTag("file", eElement).getAttribute("po");
						// //t = s.isEmpty() ? TimeHelper.zero() :
						// Time.valueOf(s);
						// t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						bbb.setPo(s);
						//
						s = getTag("file", eElement).getAttribute("duration");
						// //t = s.isEmpty() ? TimeHelper.zero() :
						// Time.valueOf(s);
						// t = s.isEmpty() ? new Time(0) : Time.valueOf(s);
						bbb.setDuration(s);

						list.add(bbb);
					}
				}
				block.setBlocks(list);
			}
			rootBlock.getBlocks().add(block);
		}

		return rootBlock;
	}

	private static String getTagValue(String sTag, Element eElement) {
		
		    NodeList nlList = eElement.getElementsByTagName(sTag);
            
		    if (nlList == null) 
            	return "";
		    
		    if (nlList.item(0) == null)
		    	return "";
            
		    nlList = nlList.item(0).getChildNodes();
            
            if (nlList == null)
            	return "";

            Node nValue = (Node) nlList.item(0);

            return nValue!=null ? nValue.getNodeValue() : "";
	}

	private static Element getTag(String sTag, Element eElement){
            //Element nValue = (Element)eElement.getElementsByTagName(sTag).item(0).getChildNodes();
		Element nValue = (Element)eElement.getElementsByTagName(sTag).item(0);
        return nValue;
	}

	public static boolean isAttrsBlock(Block block) {
		return block.getBlockAtrType().equals(TvipuskEditorWidget.SNH_TEXT) ||
			   block.getBlockAtrType().equals(TvipuskEditorWidget.SKL_TEXT);
	}
	
//	public static String getAttributesLine(Block block){
//		StringBuilder sb = new StringBuilder();
//		if (!block.getS().equals("00:00:00") || !block.getPo().equals("00:00:00")){
//			sb.append(block.getS());
//			sb.append("-");
//			sb.append(block.getPo());
//		}
//		if (!block.getBlockAtrTitle().equals("")){
//			sb.append(" ");
//			sb.append(block.getBlockAtrTitle());
//		}
//		return sb.toString();
//	}
}
